package sink

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"math/rand"
	"serial/config"
)

var reconnectCount int

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
	if reconnectCount == 0 {
		fmt.Println("MQTT首次连接成功")
	} else {
		fmt.Printf("MQTT第%d重连成功\n", reconnectCount)
		reconnectCount = 0
	}
}

var reconnectHandler mqtt.ReconnectHandler = func(client mqtt.Client, opts *mqtt.ClientOptions) {
	reconnectCount++
	fmt.Printf("MQTT开始重连,第%d次重连...\n", reconnectCount)
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
	fmt.Printf("MQTT连接异常，异常信息：%v\n", err)
}

var MqttClient mqtt.Client

func init() {
	if config.Conf.Mqtt.Enable {
		var clientId = fmt.Sprintf("go_mqtt_client_%v", rand.Intn(1000))
		mqttUrl := fmt.Sprintf("tcp://%s:%d", config.Conf.Mqtt.Broker, config.Conf.Mqtt.Port)
		fmt.Printf("MQTT尝试连接服务端[%v]\n", mqttUrl)
		opts := mqtt.NewClientOptions()
		opts.AddBroker(mqttUrl)
		opts.SetClientID(clientId)
		opts.SetUsername(config.Conf.Mqtt.Username)
		opts.SetPassword(config.Conf.Mqtt.Password)
		opts.SetReconnectingHandler(reconnectHandler)
		opts.KeepAlive = 10
		opts.OnConnect = connectHandler
		opts.OnConnectionLost = connectLostHandler
		MqttClient = mqtt.NewClient(opts)
		token := MqttClient.Connect()
		if token.Wait() && token.Error() != nil {
			fmt.Printf("mqtt连接异常，%v", token.Error())
		}
	}
}

func Publish(topic string, qos byte, retained bool, payload interface{}) bool {
	if MqttClient != nil && MqttClient.IsConnected() {
		token := MqttClient.Publish(topic, qos, retained, payload)
		return token.Wait()
	}
	return false
}
